# -*- coding: utf-8 -*-
"""
Module Description:
Date: 2017/9/8
Author: FQ
"""
import math

from pyshare.dal.gameconfig.game_env import get_config_env_set
from pyshare.utils.game_log.game_log_define import ItemLog
from pyshare.utils.time_utils import getCT, isPassDay
from pyshare.utils.game_log.log_param import LogParam
from pyshare.const.enums.item import ItemType, SpecialItem
from pyshare.const.enums.activity import AchievementClass, ActivityRecordStatus, AchievementClassName


class MoonRecordMiXin(object):
    last_enter_time = NotImplemented
    role_guid = NotImplemented
    score = NotImplemented
    lv = NotImplemented
    activity_id = NotImplemented
    award_history = NotImplemented
    moon_voucher_limit_goods_nums = NotImplemented

    def client_asdict(self):
        return {
            'Lv': self.lv,
            'Score': self.score,
            'AwardHistory': self.award_history,
            'IsFirstEnter': self.is_first_enter(),
            'MoonVoucherLimitGoodsNums': self.moon_voucher_limit_goods_nums
        }

    def is_first_enter(self):
        if not self.last_enter_time or self.last_enter_time == '2010-01-01 10:00:00':
            return True
        return False

    def add_score(self, add_value):
        """增加积分"""
        from pyshare.dal.gameconfig.query import getProfile, getProfileList
        from pyshare.dal.repository_impl import MoonAchievementCfgRepository
        from pyshare.redis_cache.area.activity_redis_cache import MoonActivityServerAchievement
        desk_cfg = getProfile('TcMoonDesk', Id=self.lv)
        add_value = int(math.ceil(add_value * desk_cfg.Ratio)) if desk_cfg else add_value
        self.score += add_value
        # 判断是否升桌
        new_cfg = getProfileList('TcMoonDesk', order_by='-NeedScore', NeedScore__lte=self.score)
        for cfg in new_cfg:
            if self.lv < cfg.Id:
                self.lv = cfg.Id
                cache = MoonActivityServerAchievement()
                for c in MoonAchievementCfgRepository.filter_by_achievementclass_type_list(
                        achievement_class=AchievementClass.Server, achievement_type_list=cfg.TypeList):
                    cache.add_achievement_reach_count(self.activity_id, c.type, 1)
            break
        return add_value

    def send_moon_voucher_daily(self, cc, is_save=True):
        """每日发送免费博饼劵"""
        if isPassDay(self.last_enter_time):
            # 隔天发送博饼券 FreeMoonVoucherDailyNum
            log_param = LogParam(rid=self.role_guid, scene='12201', remark='每日系统发放博饼券')
            goods = cc.goods.award_goods(self.role_guid, log_param, ItemType.Special,
                                         goods_count=get_config_env_set('FreeMoonVoucherDailyNum'),
                                         Id=SpecialItem.MoonVoucher)
            self.last_enter_time = getCT()
            if is_save:
                self.save()
            if goods:
                return goods.get_dict()
            else:
                return {}
        return {}

    def send_moon_voucher_limit_daily(self, is_save=True):
        """每日发送限时博饼劵"""
        if isPassDay(self.last_enter_time):
            # 隔天发送博饼券 FreeMoonVoucherDailyNum
            if self.moon_voucher_limit_goods_nums:
                self.moon_voucher_limit_goods_nums = self.moon_voucher_limit_goods_nums + \
                                                     get_config_env_set('FreeMoonVoucherDailyNum')
            else:
                self.moon_voucher_limit_goods_nums = get_config_env_set('FreeMoonVoucherDailyNum')
            log_param = LogParam(rid=self.role_guid, scene='12201', remark='每日系统发放限时博饼券')
            # 道具获得日志
            ItemLog.log_game(log_param=log_param, item_type=ItemType.Special, item_id=SpecialItem.MoonVoucherLimit,
                             item_count=self.moon_voucher_limit_goods_nums,
                             add_value=get_config_env_set('FreeMoonVoucherDailyNum'))
            self.last_enter_time = getCT()
            if is_save:
                self.save()
            return {'ItemType': ItemType.Special,
                    'ItemId': SpecialItem.MoonVoucherLimit,
                    'Count': get_config_env_set('FreeMoonVoucherDailyNum')}, self.moon_voucher_limit_goods_nums
        return {}, self.moon_voucher_limit_goods_nums


class MoonAchievementRecordMinXin(object):
    personal_status = NotImplemented
    server_status = NotImplemented
    reach_count = NotImplemented
    type = NotImplemented
    activity_id = NotImplemented
    role_guid = NotImplemented

    def server_reach_count(self):
        from pyshare.redis_cache.area.activity_redis_cache import MoonActivityServerAchievement
        return MoonActivityServerAchievement().get_one_achievement(self.activity_id, self.type)

    def status(self, a_cc):
        return self.personal_status if a_cc == AchievementClass.Personal else self.server_status

    def get_reach_count_by_class(self, c):
        """获取达成次数"""
        if c == AchievementClass.Personal:
            return self.reach_count
        else:
            return self.server_reach_count()

    def personal_achieve_status(self, config, is_red=False):
        """个人成就领取状态"""
        data = self.personal_status if self.personal_status else map(lambda x: ActivityRecordStatus.OnGoing, config)
        for index, flag in enumerate(self.personal_status):
            if flag == ActivityRecordStatus.OnGoing and self.reach_count >= config[index]:
                if is_red:
                    return True
                data[index] = ActivityRecordStatus.Done
        if is_red:
            return False
        return data

    def server_achieve_status(self, config, is_red=False):
        """全服成就领取状态"""
        data = self.server_status if self.server_status else map(lambda x: ActivityRecordStatus.OnGoing, config)
        reach_count = self.server_reach_count()
        for index, flag in enumerate(self.server_status):
            if flag == ActivityRecordStatus.OnGoing and reach_count >= config[index]:
                if is_red:
                    return True
                data[index] = ActivityRecordStatus.Done
        if is_red:
            return False
        return data

    def is_show_red(self, a_class, config):
        """根据成就class获取成就是否显示红点"""
        if a_class == AchievementClass.Personal:
            return self.personal_achieve_status(config, is_red=True)
        return self.server_achieve_status(config, is_red=True)

    def achieve_status_by_class(self, a_class, config):
        """根据成就class获取成就领奖状态"""
        if a_class == AchievementClass.Personal:
            return self.personal_achieve_status(config)
        return self.server_achieve_status(config)

    def modify_person_status(self, index, flag):
        """修改个人成就领取状态"""
        data = self.personal_status
        data[index] = flag
        self.personal_status = data

    def modify_server_status(self, index, flag):
        """修改个人全服成就领取状态"""
        data = self.server_status
        data[index] = flag
        self.server_status = data

    def modify_status(self, a_class, index, flag):
        """根据成就class修改成就领取状态"""
        if a_class == AchievementClass.Personal:
            self.modify_person_status(index, flag)
        else:
            self.modify_server_status(index, flag)

    def send_index_award_and_log(self, cc, a_c, award, index):
        """添加档位奖励"""
        log_param = LogParam(rid=self.role_guid, scene='12202', remark='领取博饼活动%s成就奖励' % AchievementClassName[a_c])
        goods = cc.goods.award_many_goods(self.role_guid, award, log_param)
        self.modify_status(a_c, index, ActivityRecordStatus.Award)
        return goods


class MoonAchievementCfgMiXin(object):
    type = NotImplemented
    achievement_class = NotImplemented
    config = NotImplemented
    award = NotImplemented

    def cfg_and_record_dict(self, record):
        data = self.asdict()
        if record:
            data['AchieveStatus'] = record.achieve_status_by_class(self.achievement_class, self.config)
            data['ReachCount'] = record.get_reach_count_by_class(self.achievement_class)
        else:
            data['AchieveStatus'] = map(lambda x: 0, self.config)
            data['ReachCount'] = 0
        return data

    def is_show_red(self, record):
        """是否有奖励可领取"""
        if not record:
            return False
        return record.is_show_red(self.achievement_class, self.config)
